package com.qf.web.controller;

import cn.dsna.util.images.ValidateCode;
import com.alibaba.fastjson.JSON;
import com.qf.domain.Address;
import com.qf.domain.Goods;
import com.qf.domain.Order;
import com.qf.domain.User;
import com.qf.service.AddressService;
import com.qf.service.GoodsService;
import com.qf.service.OrderService;
import com.qf.service.UserService;
import com.qf.service.impl.AddressServiceImpl;
import com.qf.service.impl.GoodsServiceImpl;
import com.qf.service.impl.OrderServiceImpl;
import com.qf.service.impl.UserServiceImpl;
import com.qf.utils.Base64Utils;
import com.qf.utils.RandomUtils;
import com.qf.utils.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

/**
 * projectName:myxiaomi
 * author:jww
 * time:2024/4/15 15:01
 * description:
 */
@WebServlet("/userservlet")
public class UserServlet extends BaseServlet {
    /**
     * 注册
     *
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */

    public String register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取前端数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String repassword = request.getParameter("repassword");
        String email = request.getParameter("email");
        String gender = request.getParameter("gender");
        //校验
        if (StringUtils.isEmpty(username)) {
            request.setAttribute("msg", "用户名不能为空");
            return "/register.jsp";
        }
        if (StringUtils.isEmpty(password)) {
            request.setAttribute("msg", "密码不能为空");
            return "/register.jsp";
        }
        if (!password.equalsIgnoreCase(repassword)) {
            request.setAttribute("msg", "两次密码输入不一致");
            return "/register.jsp";
        }
        if (StringUtils.isEmpty(email)) {
            request.setAttribute("msg", "邮箱不能为空");
            return "/register.jsp";
        }
        //调用业务逻辑
        UserService userService = new UserServiceImpl();
        boolean b = userService.checkUserName(username);
        if (b) {//已存在 不能注册
            request.setAttribute("msg", "用户名已存在");
            return "/register.jsp";
        }
        //友情提示：邮箱激活扩展内容 如果不写邮箱激活 flag=1;
        //flag 0未激活1激活2无效  role：0管理员1会员
        User user = new User(0, username, password, email, gender, 1, 1, RandomUtils.createActiveCode());
        try {
            userService.register(user);
            //转发重定向
            return "redirect:/registerSuccess.jsp";
        } catch (Exception e) {
            e.printStackTrace();//跟踪错误信息
            request.setAttribute("msg", "注册失败");
            return "/register.jsp";
        }

    }

    /**
     * 登录
     *
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1获取前端数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String vcode = request.getParameter("vcode");

        //后加
        String auto = request.getParameter("auto");


        //校验
        if (StringUtils.isEmpty(username)) {
            request.setAttribute("msg", "用户名不能为空");
            return "/message.jsp";
        }
        if (StringUtils.isEmpty(password)) {
            request.setAttribute("msg", "密码不能为空");
            return "/message.jsp";
        }
        if (StringUtils.isEmpty(vcode)) {
            request.setAttribute("msg", "验证码不能为空");
            return "/message.jsp";
        }
        //校验验证码
        String code = (String) request.getSession().getAttribute("vcode");
        if (!vcode.equalsIgnoreCase(code)) {

            request.setAttribute("msg", "验证码错误");
            return "/message.jsp";
        }
        try {
            //2调用业务逻辑
            UserService userService = new UserServiceImpl();
            User user = userService.login(username, password);
            //把用户存入session
            request.getSession().setAttribute("user", user);

            //后加
            System.out.println(auto);//勾选 on 不勾选 null
            if (auto != null) {
                //自动登录
                String userInfo = username + "#" + password;//bbb#123456
                //Base64处理
                userInfo = Base64Utils.encode(userInfo);
                Cookie cookie = new Cookie("userInfo", userInfo);
                //设置路径
                cookie.setPath(request.getContextPath());
                //有效日期
                cookie.setMaxAge(14 * 24 * 60 * 60);//两周自动登录
                //设置
                cookie.setHttpOnly(true);
                //回写
                response.addCookie(cookie);
            }
            //3转发重定向
            return "redirect:/index.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "用户登录失败：" + e.getMessage());
            return "/message.jsp";
        }
    }

    /**
     * 获取验证码功能
     *
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String code(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", -1);
        //1创建验证码对象
        ValidateCode validateCode = new ValidateCode(100, 28, 4, 20);
        //把验证码存入session中
        request.getSession().setAttribute("vcode", validateCode.getCode());
        System.out.println(validateCode.getCode());
        //相应给浏览器
        validateCode.write(response.getOutputStream());
        return null;
    }

    /**
     * 验证用户名是否存在
     *
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */

    public String checkUserName(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        System.out.println("username = " + username);
        if (StringUtils.isEmpty(username)) {
            response.getWriter().write("1");//1不可用
        }
        UserService userService = new UserServiceImpl();
        boolean b = userService.checkUserName(username);
        if (b) {//已存在 不可用 1
            response.getWriter().write("1");//1不可用
            return null;
        }
        response.getWriter().write("0");//0用户不存在 可以使用
        return null;
    }

    public String logOut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1把session中的信息移除
        HttpSession session = request.getSession();
        session.removeAttribute("user");
        //2session失效
        session.invalidate();
        //3删除自动登录cookie
        Cookie cookie = new Cookie("userInfo", "");
        cookie.setPath(request.getContextPath());
        response.addCookie(cookie);
        //4重定向
        return "redirect:/index.jsp";
    }

    /*-------------------------------地址模块-----------------------------------*/

    /**
     * 新增地址
     *
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    //http://localhost:8080/userservlet?method=addAddress
    public String addAddress(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1判断用户是否登录
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            return "redirect:/login.jsp";
        }
        //2获取前端数据
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String detail = request.getParameter("detail");
        //非空验证
        if (StringUtils.isEmpty(name)) {
            request.setAttribute("msg", "收货人不能为空");
            return "/message.jsp";
        }
        if (StringUtils.isEmpty(phone)) {
            request.setAttribute("msg", "收货人电话不能为空");
            return "/message.jsp";
        }
        if (StringUtils.isEmpty(detail)) {
            request.setAttribute("msg", "收货地址不能为空");
            return "/message.jsp";
        }
        try {
            //3调用业务逻辑
            AddressService addressService = new AddressServiceImpl();
            Address address = new Address(0, detail, name, phone, user.getId(), 0);
            addressService.add(address);
            return "redirect:/userservlet?method=getAddress";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "添加地址失败" + e.getMessage());
            return "/message.jsp";
        }
    }

    /**
     * 查询地址
     *
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    //http://localhost:8080/userservlet?method=getAddress
    public String getAddress(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1判断用户是否登录
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            return "redirect:/login.jsp";
        }
        try {
            //2调用业务逻辑
            AddressService addressService = new AddressServiceImpl();
            List<Address> addList = addressService.find(user.getId());
            //存值
            request.setAttribute("addList", addList);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "查询地址失败" + e.getMessage());
            return "/message.jsp";
        }
        return "/address_info.jsp";
    }

    /**
     * 删除地址
     *
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    //userservlet?method=deleteAddress&id=8
    public String deleteAddress(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1判断用户是否登录
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            return "redirect:/login.jsp";
        }
        //2获取前端数据
        String id = request.getParameter("id");
        //非空验证
        try {
            //3调用业务逻辑
            AddressService addressService = new AddressServiceImpl();
            addressService.remove(user.getId(), Integer.parseInt(id));
            return "redirect:/userservlet?method=getAddress";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "删除地址失败" + e.getMessage());
            return "/message.jsp";
        }
    }

    /**
     * 设置默认地址
     *
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    //    userservlet?method=defaultAddress&id=7
    public String defaultAddress(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1判断用户是否登录
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            return "redirect:/login.jsp";
        }
        //2获取前端数据
        String id = request.getParameter("id");
        //非空验证
        try {
            //3调用业务逻辑
            AddressService addressService = new AddressServiceImpl();
            addressService.updateLevel(user.getId(), Integer.parseInt(id));
            return "redirect:/userservlet?method=getAddress";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "设置默认地址失败" + e.getMessage());
            return "/message.jsp";
        }
    }

    //userservlet?method=updateAddress
    public String updateAddress(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1判断用户是否登录
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            return "redirect:/login.jsp";
        }
        //2获取前端数据
        String id = request.getParameter("id");
        String level = request.getParameter("level");
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String detail = request.getParameter("detail");
        //非空验证
        if (StringUtils.isEmpty(id)) {
            request.setAttribute("msg", "地址编号不能为空");
            return "/message.jsp";
        }
        if (StringUtils.isEmpty(name)) {
            request.setAttribute("msg", "收货人不能为空");
            return "/message.jsp";
        }
        if (StringUtils.isEmpty(phone)) {
            request.setAttribute("msg", "收货人电话不能为空");
            return "/message.jsp";
        }
        if (StringUtils.isEmpty(detail)) {
            request.setAttribute("msg", "收货地址不能为空");
            return "/message.jsp";
        }
        try {
            //调用业务逻辑
            AddressService addressService = new AddressServiceImpl();
            Address address = new Address(Integer.parseInt(id), detail, name, phone, user.getId(), Integer.parseInt(level));
            addressService.update(address);
            return "redirect:/userservlet?method=getAddress";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "更新地址失败" + e.getMessage());
            return "/message.jsp";
        }
    }

    /**
     * 管理员登录
     *
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    /*-------------------------------后台系统登录-----------------------------------*/
    ///userservlet?method=adminLogin
    public String adminLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //处理乱码问题
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //1获取前端数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //非空验证
        if (StringUtils.isEmpty(username)) {
            response.getWriter().write("用户名不能为空");
            return "/message.jsp";
        }
        if (StringUtils.isEmpty(password)) {
            response.getWriter().write("密码不能为空");
            return "/message.jsp";
        }
        try {
            //2调用业务逻辑
            UserService userService = new UserServiceImpl();
            User user = userService.login(username, password);
            //创建session
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            //3转发重定向
            response.sendRedirect("/admin/admin.jsp");
        } catch (Exception e) {
            e.printStackTrace();
            //3转发重定向
            response.sendRedirect("message.jsp");
        }
        return null;
    }

    //userservlet?method=adminOut
    public String adminOut(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        session.removeAttribute("user");
        session.invalidate();
        Cookie cookie = new Cookie("user", "");
        cookie.setPath(request.getContextPath());
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        return "redirect:/admin/login.jsp";
    }


    //userservlet?method=getUserList
    public String getUserList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        String username = request.getParameter("username");
        String gender = request.getParameter("gender");
        String invalidUser = request.getParameter("invalidUser");
        List<Object> params = new ArrayList<>();
        StringBuilder where = new StringBuilder("where 1=1");
        if (!StringUtils.isEmpty(username)) {
            where.append(" AND `username` LIKE ?  ");
            params.add("%" + username + "%");
        }
        if (!StringUtils.isEmpty(gender)) {
            where.append(" AND `gender`=? ");
            params.add(gender);
        }
        boolean flag = false;
        if (!StringUtils.isEmpty(invalidUser) && "true".equals(invalidUser)) {
            flag = true;
        }
        try {
            UserService userService = new UserServiceImpl();
            //List<User> userList=userService.findName(username,gender);
            List<User> userList = userService.findUserInfo(where.toString(), params, flag);
            if (userList != null && !userList.isEmpty()) {
                String json = JSON.toJSONString(userList);
                System.out.println(json);
                response.getWriter().write(json);
            }

            //request.setAttribute("userList",userList);
            return null;
            //return "/admin/userList.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "会员管理查看失败：" + e.getMessage());
            return "/message.jsp";
        }
    }

    //userservlet?method=deleteUser&id=
    public String deleteUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        if (StringUtils.isEmpty(id)) {
            request.setAttribute("msg", "删除ID不能为空");
            return "/message.jsp";
        }
        try {
            UserService userService = new UserServiceImpl();
            int did = Integer.parseInt(id);
            userService.removeId(did);
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "删除失败：" + e.getMessage());
            return "/message.jsp";
        }
    }
}
